﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace VectorCalculator
{
    public class Convertor
    {
        public static float[] ToVector(string embeddingString)
        {
            if (string.IsNullOrEmpty(embeddingString))
                return null;

            embeddingString = embeddingString.Trim('[', ']'); // 去除方括号   
            embeddingString = embeddingString.Replace(" ", ""); // 去除空格
            embeddingString = embeddingString.Replace("\r\n", ""); // 去除换行符

            var arr = embeddingString.Split(',');
            float[] result = new float[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                result[i] = float.Parse(arr[i]);
            }
            return result;
        }


        public static float[] ToVector(object target)
        {
            if (target == null)
            {
                return [];
            }

            if (target is string embedding)
            {
                return ToVector(embedding);
            }

            if (target is ArrayList arr)
            {
                return [.. arr.ToArray().Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if (target is IEnumerable enumerable)
            {
                return [.. enumerable.Cast<object>().Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if (target is float[] arrFloat)
            {
                return arrFloat; // 如果已经是浮点数组，直接返回
            }

            if(target is double[] arrDouble)
            {
                return arrDouble.Select(x => (float)x).ToArray(); // 如果是双精度数组，转换为浮点数组
            }

            if (target is IList list)
            {
                return [.. list.Cast<object>().Select(x => (x is float) ? (float)x : float.Parse(x.ToString()))]; // 其他都需要转换为浮点数
            }

            if(target is JsonArray jsonArray)
            {
                return [.. jsonArray.Select(x => (x is JsonValue jsonValue) ? (float)jsonValue : float.Parse(x.ToString()))]; // 如果是JsonArray类型，转换为浮点数组
            }

            return [];

        }
    }
}
